package org.luxor.commons.zookeeper.lock;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.luxor.commons.core.exception.GlobalLockException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 分布式可重入排他锁
 *
 * @author Mr.Yan  @date: 2020/12/25
 */
public class GlobalLockTemplate {
    private static final Logger logger = LoggerFactory.getLogger(GlobalLockTemplate.class);
    private CuratorFramework curatorFramework;

    public GlobalLockTemplate(CuratorFramework curatorFramework) {
        this.curatorFramework = curatorFramework;
    }

    /**
     * 获取 分布式排他锁
     *
     * @param path 锁的唯一路径
     * @throws GlobalLockException ZK errors, connection interruptions
     */
    public InterProcessMutex lock(String path) throws GlobalLockException {
        try {
            InterProcessMutex mutex = new InterProcessMutex(this.curatorFramework, path);
            mutex.acquire();
            logger.trace(">>>  获取分布式锁(GlobalLock)完成. path:{}", path);
            return mutex;
        } catch (Exception e) {
            throw new GlobalLockException("获取分布式锁异常", e);
        }
    }

    /**
     * 释放 分布式排他锁
     *
     * @param mutex 分布式可重入排他锁
     */
    public void releaseLock(InterProcessMutex mutex) throws GlobalLockException {
        try {
            mutex.release();
            logger.trace("<<< 释放分布式锁(GlobalLock)完成.");
        } catch (Exception e) {
            throw new GlobalLockException("释放分布式锁异常", e);
        }
    }

}
